package cn.hsj.service;


import cn.hsj.properties.IpProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


public class IpCountService {
     private HashMap<String ,Integer> countMap = new HashMap<>();
     @Autowired
     ///当前request对象的注入工作 由使用当前starter的工程 提供自动装配
     private HttpServletRequest httpServletRequest;
    public void count(){
        //每次调用当前操作，就记录当前访问的ip，然后累加访问次数
        //1.获取当前ip地址

        String ip = httpServletRequest.getRemoteAddr();
        System.out.println("-------------------"+ip);
        Integer count = countMap.get(ip);
        //2.根据ip地址从map取值。并+1
        if(count == null){
            countMap.put(ip,1);
        }else {
            countMap.put(ip, count + 1);
        }
    }

    @Resource
    private IpProperties ipProperties;
    //拿到 application.yml 里配置的内容，来设置 监控内容信息的表达方式

    @Scheduled(cron = "0/5 * * * * ?")
    public void print(){
        if(ipProperties.getModel().equals(IpProperties.LogModel.DETAIL.getValue())){
            // 配置文件里开启了明细模式 ,那就输出明细内容
            System.out.println("                IP 访问监控");
            System.out.println("+-----ip-address-----+--num--+");
            for (Map.Entry<String, Integer> stringIntegerEntry : countMap.entrySet()) {
                String key = stringIntegerEntry.getKey();
                Integer value = stringIntegerEntry.getValue();
                System.out.printf("|%18s  |%5d  |%n",key,value);
            }
            System.out.println("+--------------------+-------+");
        }else if(ipProperties.getModel().equals(IpProperties.LogModel.SIMPLE.getValue())){
            // 配置文件 设置了 简单模式， 那就输出简单内容
            for (String key: countMap.keySet()){
                System.out.println(key);
            }
        }

        //判断 配置文件 是否设置了清空
        if(ipProperties.getCycleRest()){
            countMap.clear();
        }


    }


}
